package com.xw.bo.ks.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.api.sharding.complex.ComplexKeysShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.complex.ComplexKeysShardingValue;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * 复合分片算法
 * 提供对SQL语句中的=，in和between and的分片操作，支持【多分片健】
 *
 * @author： XW -> ~
 * @create： 2023/11/8 17:36
 */
@Slf4j
public class CustomComplexKeysShardingAlgorithm implements ComplexKeysShardingAlgorithm<Long> {

    @Override
    public Collection<String> doSharding(Collection<String> collection, ComplexKeysShardingValue<Long> complexKeysShardingValue) {

        Collection<Long> createdAtValues = this.getShardingValue(complexKeysShardingValue, "order_create_time");

//        Collection<Long> userIdValues = this.getShardingValue(complexKeysShardingValue,"user_id");

        Set<String> shardingSuffix = new LinkedHashSet<>();

        for (Long cAt : createdAtValues) {
            String dayTime = DateUtils.formatDateToString(new Date(cAt * 1000), DateUtils.DATE_PATTERN_TABLE);
            log.info("dayTime = {}", dayTime);
            for (String databaseName : collection) {
                if (databaseName.endsWith(dayTime)) {
                    shardingSuffix.add(databaseName);
                }
            }
        }

        //对两个分片键取模的方式
//        for (Long userId : userIdValues) {
//            for (Long orderId : orderIdValues) {
//                //拼接的效果，0_0,0_1,1_0,1_1，1去匹配product_order_0_0,product_order_0_1,product_order_1_0,product_order_1_1
//                String suffix = userId % 2 + "_" + orderId % 2;
//                for (String databaseName : collection) {
//                    if (databaseName.endsWith(suffix)) {
//                        shardingSuffix.add(databaseName);
//                    }
//                }
//            }
//        }

        // 没有命中分片，就随机一个表给他，防止出现异常
        if (CollectionUtils.isEmpty(shardingSuffix)) {
            for (String dataSourceName : collection) {
                shardingSuffix.add(dataSourceName);
                break;
            }
        }

        return shardingSuffix;
    }

    /**
     * shardingValues：分片属性
     * logicTableName：逻辑表
     * columnNameAndShardingValuesMap 存储多个分片健 包括key-value
     * value：分片value，66和99
     *
     * @param shardingValues
     * @param key
     * @return
     */
    private Collection<Long> getShardingValue(ComplexKeysShardingValue<Long> shardingValues, String key) {

        Collection<Long> valueSet = new ArrayList<>();

        Map<String, Collection<Long>> columnNameAndShardingValuesMap = shardingValues.getColumnNameAndShardingValuesMap();

        if (columnNameAndShardingValuesMap.containsKey(key)) {
            valueSet.addAll(columnNameAndShardingValuesMap.get(key));
        }
        return valueSet;
    }

}
